package com.hncboy.chatgpt.front.service.impl;



import com.hncboy.chatgpt.front.domain.Message;
import com.hncboy.chatgpt.front.service.ChatCacheService;
import com.hncboy.chatgpt.front.util.ChatCache;
import com.hncboy.chatgpt.front.util.ChatResult;
import com.hncboy.chatgpt.front.util.ChoiceModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 默认服务实现 Cache
 */
@Slf4j
@Service
public class DefaultChatCacheServiceImpl implements ChatCacheService {


    @Override
    public List<Message> history(String chatId, Integer limit) {
        List<Message> list = new ArrayList<>(ChatCache.get(chatId));
        int listSize = list.size();
        int startIndex = 0;
        if (listSize > limit){
            startIndex = listSize - limit;
        }
        return list.subList(startIndex,listSize);
    }

    @Override
    public void write(String chatId, Message message) {
        List<Message> messages = ChatCache.get(chatId);
        messages.add(message);
        ChatCache.put(chatId,messages);
    }


    @Override
    public String simpleResult(ChatResult result) {
        // 获取返回结果
        List<ChoiceModel> choices = result.getChoices();
        // 获取第一条结果
        ChoiceModel choice = choices.get(0);
        // 获取消息
        Message message = choice.getMessage();
        // 返回内容
        return message.getContent();
    }
}
